package com.sugar.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sugar.ssm.bean.Employee;
import com.sugar.ssm.dto.EmpDTO;
import com.sugar.ssm.dto.Msg;
import com.sugar.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tangyx
 * @date 2022/3/27 20:49
 * +
 */
@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    //查询员工  这种方式是全页面请求
//    @RequestMapping("/emps")
//    public  String getEmps(
//            @RequestParam(value = "pn",defaultValue = "1")Integer pn,
//            Model model
//    ){
//        PageHelper.startPage(pn,5);
//        List<Employee> emps = employeeService.getAll();
//        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
//        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
//        PageInfo page = new PageInfo(emps, 5);
//        model.addAttribute("pageInfo", page);
//        return "list";
//    }

//    返回值为json
//    使用ResponseBody 就是不跳转添转页面 直接返回json
    @ResponseBody
    @RequestMapping("/emps")
    public Msg getEmpsbyJson(
            @RequestParam(value = "pn",defaultValue = "1")Integer pn
    ){
        PageHelper.startPage(pn,5);
        List<Employee> emps = employeeService.getAll();
        PageInfo page = new PageInfo(emps, 5);

//      之所以返回的数据是标准的json格式 是因为 jackson
        return Msg.success().add("pageInfo",page);
    }

    @PostMapping("emp")
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
        if(result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            for (FieldError fieldError:result.getFieldErrors()) {
                    map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.wrong().add("errorFields",map);
        }
        employeeService.saveEmp(employee);
        return Msg.success();
    }

    @ResponseBody
    @RequestMapping("/checkuser")
    public Msg checkuser(@RequestParam("empName") String empName){
        boolean rs = employeeService.checkUser(empName);
        //后端也加上用户名合法化的验证
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";

        if(!empName.matches(regx)){
            return Msg.wrong().add("va_msg","用户名必须是6-16位数字和字母的组合或者2-5位中文");
        }
        if(rs){
            return Msg.success();
        }else
            return Msg.wrong().add("va_msg","用户名已经存在，不可用");
    }

    @ResponseBody
    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    public Msg getEmp(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp",employee);
    }

//    此处的路径中的变量id之所以使用empId 是为了封装数据到employee中 id不为null
    @ResponseBody
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    public Msg updateEmp(Employee employee){
        employeeService.updateEmp(employee);
        return Msg.success();
    }

    @ResponseBody
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.DELETE)
    public Msg deleteEmp(@PathVariable("empId")String ids){
//        employeeService.deleteOneEmp(ids);
        if(ids.contains("-")){
            List<Integer> list_emps = new ArrayList<>();
            String[] emps = ids.split("-");
            for (String emp:emps) {
                list_emps.add(Integer.valueOf(emp));
            }
            employeeService.deleteManyEmp(list_emps);
        }else {
            employeeService.deleteOneEmp(Integer.valueOf(ids));
        }
        return Msg.success();
    }
}
